<template>
	<view>
		<view class="template-view location-info-top">
			<view class="info" @tap="getLocation">{{location.address || ''}}</view>
			<view class="operate wanl-bg-orange" @tap="addAddress('add')">新增地址</view>
		</view>
		<view class="edgeInsetTop"></view>
		<view class="template-view pick-top">
			<view class="address-view flex-between items-center" @click="$wanlshop.auth('/pages/user/address/address?source=3',{})">
				<view>
					<view class="address-tag" style="background: #00d969;color:#fff;">
						寄
					</view>
				</view>
				<view style="margin-left: 10rpx;width:80%;">
					<view class="user-info">
						{{seller.adName || '暂无地址'}} {{seller.adMobile || ''}}
					</view>
					<view class="address-info">
						{{seller.adProvince || '点击选择地址'}}{{seller.adArea || ''}}{{seller.adDetail || ''}}{{seller.adHouseNumber || ''}}
					</view>
				</view>
				<view>
					<u-icon name="arrow-right" size="16"></u-icon> 
				</view>
			</view>
			<view style="width:84%;height: 2rpx;background: #eee;margin:20rpx 0rpx;left:8%;position: relative;">

			</view>
			<view class="address-view flex-between items-center" @click="$wanlshop.auth('/pages/user/address/address?source=4',{})">
				<view>
					<view class="address-tag" style="background: #3c9cff;color:#fff;">
						收
					</view>
				</view>
				<view style="margin-left: 10rpx;width:80%;">
					<view class="user-info">
						{{query.adName || '暂无地址'}} {{query.adMobile || ''}}
					</view>
					<view class="address-info">
						{{query.adProvince || '点击选择地址'}}{{query.adArea || ''}}{{query.adDetail || ''}}{{query.adHouseNumber || ''}}
					</view>
				</view>
				<view>
					<u-icon name="arrow-right" size="16"></u-icon>
				</view>
			</view>
			<view v-if="reason" class="flex-center"
				style="width:100%;background: rgba(255,0,0,0.3);color:#fff;font-size: 26rpx;border-radius: 20rpx;margin-top: 20rpx;padding:10rpx 0rpx;">
				<u-icon name="info-circle-fill" color="#fff" :label="'当前地址不可发货/收货，原因是'+reason+'！'" labelColor="#fff"
					labelSize="12"></u-icon>
			</view>
			<view class="margin-top-xs" style="color:red;font-size: 24rpx;text-align: center;">
					地址添加成功后请确认是否正确，如有误，请及时修正！
			</view>
		</view>		
		<view class="template-view">
			<u-cell-group :border="false">
				<u-cell :border="false" title="类型" :customStyle="{'padding':'20rpx 0rpx;'}">
					<view slot="right-icon" @click="show=true">
						<u-icon name="arrow-right" :label="file" labelPos="left" size="16"></u-icon>
						 <view class="flex-end items-center" style="flex-wrap: wrap;">
							<view style="margin-bottom: 10rpx;margin-left: 10rpx;display: none;" v-for="(item,index) in columns[0]" :key="index">
								<u-tag type="primary" :plain="true"
									:text="item" size="mini"></u-tag>
							</view>
						</view>
					</view>
				</u-cell>
				<u-cell :border="false" title="重量(KG)" :customStyle="{'padding':'20rpx 0rpx;'}">
					<view slot="right-icon">
						<u-number-box v-model="weight" @change="valChange" color="indianred" iconStyle="indianred">
						</u-number-box>
					</view>
				</u-cell>
				<u-cell :border="false" title="体积(CM)" :customStyle="{'padding':'20rpx 0rpx;'}">
					<view slot="right-icon">
						<view class="flex-center items-center" style="font-size: 24rpx;color:indianred;">
							长
							<u-input type="number" placeholder="CM" border="bottom" :customStyle="{'display': 'inline-block', 'width':'100rpx'}"
								v-model="length" inputAlign="center"></u-input>

							宽
							<u-input type="number" placeholder="CM" border="bottom" :customStyle="{'display': 'inline-block', 'width':'100rpx'}"
								v-model="width" inputAlign="center"></u-input>

							高
							<u-input type="number" placeholder="CM" border="bottom" :customStyle="{'display': 'inline-block', 'width':'100rpx'}"
								v-model="height" inputAlign="center"></u-input>
						</view>
					</view>
				</u-cell>
				<u-cell :border="false" title="备注" :customStyle="{'padding':'20rpx 0rpx;'}">
					<view slot="right-icon">
						<view class="flex-center items-center" style="font-size: 24rpx;color:indianred;">
							<u-input type=""  border="bottom" placeholder="选填"
								v-model="bill_remark" inputAlign="center"></u-input>
						</view>
					</view>
				</u-cell>
			<!-- 	<u-cell :border="false" title="保价金额(元)（保价丢件可赔偿）" :customStyle="{'padding':'20rpx 0rpx;'}">
					<view slot="right-icon">
						
						<view class="flex-center items-center" style="font-size: 24rpx;color:indianred;">
				
							<u-input type="number" placeholder="0" border="bottom" :customStyle="{'width':'120rpx'}"
								v-model="insured" @change="valChange"  inputAlign="center"></u-input>
						</view>
					</view>
				</u-cell> -->
				<!-- <u-cell :border="false" title="优惠券" :customStyle="{'padding':'20rpx 0rpx;'}">
					<view slot="right-icon">
						<u-icon name="arrow-right" label="您有1张优惠券可选" labelPos="left" size="16"></u-icon>
					</view>
				</u-cell> -->
			</u-cell-group>			
		</view>

		<view class="flex-center items-center"
			style="width:100%;margin:0 auto;color:#999;text-align: center;padding-top:20rpx;font-size: 26rpx;display: flex;">
			<view style="width:6%;padding-left: 10%;">
				<u-radio-group @change="groupChange" v-model="xieyi">
					<u-radio shape="circle" name="success" activeColor="#3c9cff"></u-radio>
				</u-radio-group>
			</view>
			<view style="flex:1;margin-right: 35%;">
				我已阅读并同意<label style="color:blue;" @click="$wanlshop.auth('/pages/order/xieyi')">《用户协议》</label>
			</view>

		</view>

		<view class="template-view" v-if="logList && logList.length>0">
			<u-cell-group :border="false">
				<u-cell v-for="(item,index) in logList" :key="index" :border="false" :icon="item.icon"
					:customStyle="{'padding':'20rpx 0rpx;'}"
					:iconStyle="{'width':'60rpx','height':'60rpx','border-radius':'50%'}">
					<view slot="label" style="font-size: 30rpx;color:#000;margin-left: 10rpx;">
						{{item.name}}
					</view>
					<view slot="label" style="font-size: 26rpx;color:#999;margin-left: 10rpx;">
						预估金额：<label style="color:indianred;">￥{{item.totalFee}}</label>
					</view>
					<view slot="label" style="font-size: 22rpx;color:#999;margin-left: 10rpx;">
						<text>快递余额：</text><label style="color:indianred;">￥{{item.expbalance || 0}}</label>
						<text style="margin-left: 3rpx;">已抵扣：</text><label style="color:indianred;" >￥{{item.expsub || 0}}</label>
					</view>
					<view slot="right-icon">
						<u-tag text="下单" size="mini" type="primary" @click="confirmCreateOrder(item, item.shipperCode,item.name,item.totalFee,item.expbalance,item.expsub)"></u-tag>
					</view>
				</u-cell>
			</u-cell-group>
		</view>
		<view class="template-view" style="color:#999;font-size: 24rpx;text-align: center;" v-else>
			选择寄件收件地址后系统自动读取快递公司信息			
		</view>
		<view class="template-view">
			<view class="flex-center"
				style="width:96%;margin:0 auto;color:indianred;font-size: 26rpx;border-radius: 20rpx;margin-top: 20rpx;padding:10rpx 0rpx;">
				如果重量存在误差会导致运费计算不精确,快递方收件后可能会额外收取运费,该费用平台会通知您进行补差
				<!-- <u-icon name="info-circle-fill" color="#fff" label="请确保重量和体积正确无误,如果存在误差会导致运费计算不正确,快递方收件后会额外收取运费,该费用平台会通知您进行补差" labelColor="#fff"
					labelSize="12"></u-icon> -->
			</view>
		</view>		

		<u-divider :dashed="true"></u-divider>
		<u-picker :show="show" :columns="columns" @confirm="firmPicker" @cancel="show=false"></u-picker>
		<uni-popup ref="createOrderPopup" mask-background-color="rgba(0, 0, 0, 0.4)">
			<view class="wanl-createOrder-popup bg-white radius-bock text-center">
				<view class="avatar">
					<image src="/static/images/user/remind.png" mode="aspectFill"></image>
				</view>
				<view class="margin-tb text-xxl wanl-black text-bold">下单必读</view>
				<scroll-view style="max-height: 50vh" scroll-y="true">
					<view class="text-left" v-html="order.channelExplain"></view>
				</scroll-view>
				<view class="margin-top-sm">
					<button class="cu-btn sl radius-bock bg-no" @tap="cancelOrder">取消下单</button>
					<button type="primary" class="cu-btn sl radius bg-no margin-left" @tap="createOrder">我已同意</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import wanlshop_config from '../../../common/config/config';
	export default {
		components: {
		},
		data() {
			return {
				show: false,
				columns: [
					['日用品', '文件', '化妆品', '图书', '衣服鞋帽', '箱包', '其他']
				],
				file: '请选择',
				length: 1,
				width: 1,
				height: 1,
				bill_remark:'',
				insured:0,
				xieyi: 'null',
				weight: 1,
				noticeList: [],
				seller: {},
				query: {},
				reason: '',
				logList: [],
				uid: 0,
				addressList: [],
				location: {},
				order: {}
			}
		},
		onLoad(options) {
			
		},
		onShow() {
			
		},
		methods: {
			init() {
				var that = this;
				that.file = (uni.getStorageSync('filePicker') || '请选择');
				

				this.xieyi = uni.getStorageSync('xieyi') || 'null';
			},
			loadData(address) {
				var that = this;
				if(address.source == 3) {
					this.$set(this.seller,'adName',address.name)
					this.$set(this.seller,'adMobile',address.mobile)
					this.$set(this.seller,'adProvince',address.province)
					this.$set(this.seller,'adCity',address.city)
					this.$set(this.seller,'adArea',address.district)
					this.$set(this.seller,'adDetail',address.address)
					this.$set(this.seller,'adHouseNumber',address.address)
					
				}
				if(address.source == 4) {
					this.$set(this.query,'adName',address.name)
					this.$set(this.query,'adMobile',address.mobile)
					this.$set(this.query,'adProvince',address.province)
					this.$set(this.query,'adCity',address.city)
					this.$set(this.query,'adArea',address.district)
					this.$set(this.query,'adDetail',address.address)
					this.$set(this.query,'adHouseNumber',address.address)
				}

				if(this.seller && this.query && this.seller.adDetail && this.query.adDetail) {
					this.$api.get({
						url: wanlshop_config.appurl2 + '/kuaidi/channelList',
						loadingTip: '更新列表中...',
						data:{
							userid:uni.getStorageSync('userid'),
							insured:this.insured,
							sender: this.seller.adName,
							senderMobile: that.seller.adMobile,
							senderProvince: that.seller.adProvince,
							senderCity: that.seller.adCity,
							senderCounty:that.seller.adArea,
							senderLocation:that.seller.adDetail,
							receiver:that.query.adName,
							receiverMobile:that.query.adMobile,
							receiveProvince:that.query.adProvince,
							receiveCity:that.query.adCity,
							receiveLocation:that.query.adDetail,
							weight:that.weight,
							packageCount:1
							
						},
						success: res => {
							// var resp = JSON.parse(res);
							if (res && res['result']) {
								var result = res['result']
								// console.log(resp)
								result.forEach(item => {
									var chan = this.logList.find(_ => _.key == item.channelId);
									var itemTemp ={}
									if (!chan) {
										this.$set(itemTemp,'icon',item.channelLogoUrl)
										this.$set(itemTemp,'name',item.tagType)
										this.$set(itemTemp,'shipperCode',item.channelId)
										this.$set(itemTemp,'totalFee',item.totalFreight)
										itemTemp.expbalance = item.expbalance;
										itemTemp.expsub = item.expsub;
										this.logList.push(Object.assign(item, itemTemp));
									}
								})
							} else {
								that.$wanlshop.msg(res.Message);
							}
							
						},
						error: err => {
						        console.error('网络请求失败', err);
						        // 在此处可以添加处理网络请求失败的逻辑
						    }
					});
					this.$forceUpdate();
				}
				// 在异步操作后手动强制更新视图
				this.$forceUpdate();
				
			},
			firmPicker(e) {
				//console.log('firmPicker', e)
				this.file = e.value[0];
				uni.setStorageSync('filePicker', e.value[0]);
				this.show = false;
			},
			loginClose() {
				// this.isLogin = true;
				this.init();
			},
			groupChange(e) {
				console.log(e);
				this.xieyi = e;
				uni.setStorageSync('xieyi', this.xieyi)
			},
			reloadAddress(name) {
				var that = this;
				if (name == 'none') {
					that.$uti.alert('无效选择');
					return;
				}
				this[name] = uni.getStorageSync(name) || [];

				if (this.seller && this.seller.id && this.query && this.query.id) {
					that.$http.post('Order/AreaVerification', {
						r_ProvinceName: that.query.adProvince,
						r_CityName: that.query.adCity,
						r_ExpAreaName: that.query.adArea,
						r_Address: that.query.adDetail + that.query.adHouseNumber,
						s_ProvinceName: that.seller.adProvince,
						s_CityName: that.seller.adCity,
						s_ExpAreaName: that.seller.adArea,
						s_Address: that.seller.adProvince + that.seller.adHouseNumber,
					}, function(data) {
						var res = JSON.parse(data.Data);
						that.reason = res.Success ? '' : res.Reason;
					})

					that.getEstimatedFreight();
				}
			},
			valChange(e) {
				console.log('当前值为: ' + e.value);
				this.weight = e.value;
				this.getEstimatedFreight();
			},
			getEstimatedFreight() {
				var that = this;
				that.logList = [];
				if(this.seller && this.query && this.seller.adDetail && this.query.adDetail) {
					this.$api.get({
						url: wanlshop_config.appurl2 + '/kuaidi/channelList',
						loadingTip: '加载中...',
						data:{
							userid:uni.getStorageSync('userid'),
							insured:this.insured,
							bill_remark:this.bill_remark,
							sender: that.seller.adName,
							senderMobile: that.seller.adMobile,
							senderProvince: that.seller.adProvince,
							senderCity: that.seller.adCity,
							senderCounty:that.seller.adArea,
							senderLocation:that.seller.adDetail,
							receiver:that.query.adName,
							receiverMobile:that.query.adMobile,
							receiveProvince:that.query.adProvince,
							receiveCity:that.query.adCity,
							receiveLocation:that.query.adDetail,
							weight:that.weight,
							packageCount:1
							
						},
						success: res => {
							// var resp = JSON.parse(res);
							if (res && res['result']) {
								var result = res['result']
								//console.log(resp)
								result.forEach(item => {
									var chan = this.logList.find(_ => _.key == item.channelId);
									var itemTemp ={}
									if (!chan) {
										this.$set(itemTemp,'icon',item.channelLogoUrl?item.channelLogoUrl:'')
										this.$set(itemTemp,'name',item.tagType)
										this.$set(itemTemp,'shipperCode',item.channelId)
										this.$set(itemTemp,'totalFee',item.totalFreight)
										itemTemp.expbalance = item.expbalance;
										itemTemp.expsub = item.expsub;
										this.logList.push(Object.assign(item, itemTemp));
									}
								})
							} else {
								that.$wanlshop.msg(res.Message);
							}
							
						},
						error: err => {
						        console.error('网络请求失败', err);
						        // 在此处可以添加处理网络请求失败的逻辑
						    }
					});
					//console.log(this.logList);
					this.$forceUpdate();
				}
			},
			// 下单弹窗
			confirmCreateOrder(order, channelId,name,totalFee,expbalance,expsub) {
				var that = this;
				console.log('协议', that.xieyi)
				if (that.xieyi != 'success') {
					that.$wanlshop.msg('请阅读并同意用户协议');
					return;
				}
				
				if (that.file == '请选择') {
					that.$wanlshop.msg('请选择类型');
					return;
				}
				if(that.seller.adCity != that.query.adCity) {
					that.$wanlshop.msg('同城急送暂不支持城际快递，请重新选择');
					return;
				}
				this.order = order;
				this.$refs.createOrderPopup.open();
			},
			cancelOrder() {
				this.order = null;
				this.$refs.createOrderPopup.close();
			},
			createOrder() {
				var that = this;
				this.$refs.createOrderPopup.close();
				if (this.seller && this.query && this.order) {
					this.$api.get({
						url: wanlshop_config.appurl2 + '/kuaidi/preSendKuaidi',
						loadingTip: '下单中...',
						data:{
							...this.order,
							userid:uni.getStorageSync('userid'),
							channelId:this.order.shipperCode,
							itemName:this.order.name,
							order_price:this.order.totalFee,
							insured:this.insured,
							bill_remark:this.bill_remark,
							sender: that.seller.adName,
							senderMobile: that.seller.adMobile,
							senderProvince: that.seller.adProvince,
							senderCity: that.seller.adCity,
							senderCounty:that.seller.adArea,
							senderLocation:that.seller.adDetail,
							receiver:that.query.adName,
							receiverMobile:that.query.adMobile,
							receiveProvince:that.query.adProvince,
							receiveCity:that.query.adCity,
							receiveLocation:that.query.adDetail,
							weight:that.weight,
							itemName:that.file,
							packageCount:1,
							expbalance:this.order.expbalance || 0,
							expsub:this.order.expsub || 0,
						}, 
						success: res => {
							// var resp = JSON.parse(res);
							if(res && res.code + '' === '1') {
								this.$wanlshop.to(`/pages/user/money/pay?token=${res.token}&type=${res.type}&data=${JSON.stringify(res.paylist)}`);
							} else {
								that.$wanlshop.msg(res.message);
							}
							// if (res && res['result']) {
							// 	var result = res['result']
							// 	//测试null 调起支付的情况，默认返回null
							// 	if (result.collectionValue == null) {
							// 		console.log(res)
							// 		console.log(res.token)
							// 		console.log(res.type)
							// 		console.log(res.paylist)
							// 	 	//that.weChatPay(result);
							// 		this.$wanlshop.to(`/pages/user/money/pay?token=${res.token}&type=${res.type}&data=${JSON.stringify(res.paylist)}`);
							// 	 } else {
							// 	 	that.$wanlshop.msg(res.message);
							// 	}
							// } else {
							// 	that.$wanlshop.msg(res.message);
							// }
						},
						error: err => {
							that.$wanlshop.msg('网络请求失败');
						        console.error('网络请求失败', err);
						        // 在此处可以添加处理网络请求失败的逻辑
						}
						
					});
				} else {
					that.$wanlshop.msg('请先选择地址');
				}
			},
			weChatPay(data) {
				uni.requestPayment({
					provider: 'wxpay',
					nonceStr: data.nonceStr,
					package: data.package,
					paySign: data.paySign,
					signType: data.signType,
					timeStamp: data.timeStamp,
					success: (res) => {
						console.log('success:' + JSON.stringify(res));
						uni.showToast({
							title: '支付成功！',
							duration: 2000
						});
						uni.reLaunch({
							url: '/pages/order/list'
						})
					},
					fail: (err) => {
						console.log('fail:' + JSON.stringify(err));
						uni.showToast({
							title: '已取消支付！',
							icon: 'none',
							duration: 2000
						});
					}
				});
			},
			getLocation() {
				// 加载位置
				uni.getLocation({
					type: 'wgs84',
					geocode: true,
					success: mres=> {
						// location: mres.longitude+','+mres.latitude
					}
				});
			},
			// 新增地址
			addAddress(type, item) {
				this.$wanlshop.to(`/pages/user/address/addressManage?type=${type}&data=${JSON.stringify(item)}`);
			},
		},
	} 
</script>

<style>
	@import url('index.css');
	/* 橙色 */
	.wanl-bg-orange {
		color: white;
		background-image: linear-gradient(-90deg, #ff4950 0, #ff8123 100%);
	}
	.location-info-top {
		display: flex;
		justify-content: space-between;
		background-color: transparent;
		padding: 0;
		margin-bottom: -10px;
		margin-top: 0;
		border-bottom-right-radius: 0;
	}
	.location-info-top > .operate {
		padding: 5rpx 40rpx;
		border-radius: 10rpx 10rpx 0 0;
	}
	.template-view.pick-top {
		border-top-right-radius: 0;
	}
	.wanl-createOrder-popup {
		width: 80%;
		margin: 0 auto;
		padding: 50rpx;
	}
	.wanl-createOrder-popup .avatar {
		position: absolute;
		top: -50rpx;
		left: 50%;
		transform: translateX(-50%);
	}
	
	.wanl-createOrder-popup .avatar image {
		border-radius: 9999px;
		overflow: hidden;
		height: 100rpx;
		width: 100rpx;
	}
	.wanl-createOrder-popup .read-content {
		max-height: 50vh;
		overflow: auto;
	}
</style>
